﻿using System;
using System.Net;
using System.Net.Sockets;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.Communication.Base;
using UtilZ.Dotnet.Ex.Communication.Net.Base;
using UtilZ.Dotnet.Ex.Communication.Net.Tcp;
using UtilZ.Dotnet.Ex.Log;

namespace ConAppCore
{
    internal class TestNetTcpClient
    {
        private static NetTcpClient _client = null;
        public static void Test()
        {
            //TestEndPointEquals();


            IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.96"), 26101);
            var initPara = new NetTcpClientInitPara(new TestNetTcpClientUnpacker(), remoteEndPoint)
            {
                LocalEndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.96"), 2000),
                ReceiveDataMode = ThreadMode.Async,
            };
            _client = new NetTcpClient(initPara);
            _client.ConnectChanged += _client_ConnectChanged;
            _client.ConnectAsync();



            //
            Console.ReadKey();
        }

        private static void _client_ConnectChanged(object sender, NetConnectedChangedArgs e)
        {
            switch (e.Status)
            {
                case ConnectionStatus.Opened:
                    Console.WriteLine("Opened");
                    break;
                case ConnectionStatus.Closed:
                    Console.WriteLine("Closed");
                    break;
            }
        }

        private static void TestEndPointEquals()
        {
            EndPoint dnsEndPoint1 = new DnsEndPoint("127.0.0.1", 25);
            EndPoint dnsEndPoint2 = new DnsEndPoint("127.0.0.1", 25);
            var ret11 = dnsEndPoint1 == dnsEndPoint2;
            var ret12 = dnsEndPoint1.Equals(dnsEndPoint2);

            EndPoint unixEndPoint1 = new UnixDomainSocketEndPoint(@"\root\abc");
            EndPoint unixEndPoint2 = new UnixDomainSocketEndPoint(@"\root\abc");
            var ret21 = unixEndPoint1 == unixEndPoint2;
            var ret22 = unixEndPoint1.Equals(unixEndPoint2);

            EndPoint ipEndPoint1 = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);
            EndPoint ipEndPoint2 = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);
            var ret31 = ipEndPoint1 == ipEndPoint2;
            var ret32 = ipEndPoint1.Equals(ipEndPoint2);
        }

        internal class TestNetTcpClientUnpacker : UnpackerAbs
        {
            protected override int PrimitiveUnPackge(IUnpackerPara unpackerPara)
            {
                var netPara = (NetTcpUnpackerPara)unpackerPara;
                if (netPara.DataLength == 0)
                {
                    return 0;
                }
                //throw new NotImplementedException();
                Loger.Info($"收到数据:{netPara.DataLength}");
                return netPara.DataLength;
            }
        }
    }
}
